import React, { useState, useCallback, useImperativeHandle } from "react";
import { Form, Tag, Input, Modal } from "antd";

const { CheckableTag } = Tag;

function SearchTool(props, ref) {

    const [componentTypes, setComponentTypes] = useState([]);

    let params = {};

    useImperativeHandle(
        ref,
        () => ({
            getParams() {
                return params;
            },
        }),
        [params],
    )

    const handleChange = useCallback(
        (tag, checked) => {
            setComponentTypes(checked ? [...componentTypes, tag] : componentTypes.filter(t => t.id !== tag.id));
        }, [componentTypes]
    );

    const onFinish = useCallback((values) => {
        values = { ...values, componentTypes }
        params = values;
        props.handleFinish();
    }, [componentTypes]);

    const onFinishFailed = useCallback((errorInfo) => {
        Modal.error({
            title: '出错了',
            content: '抱歉，出错了，请联系管理员~',
        });
    }, []);

    return <Form
        name="basic"
        initialValues={{
            componentTypes: []
        }}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
        autoComplete="off">
        <Form.Item
            label="组件类型"
            name="componentTypes">
            <Form.Item>
                {
                    props.tags.map(tag => (
                        <CheckableTag
                            key={tag.id}
                            checked={Array.isArray(componentTypes) && componentTypes.map(tt => tt.id).indexOf(tag.id) > -1}
                            onChange={checked => handleChange(tag, checked)}>
                            {tag.name}
                        </CheckableTag>
                    ))
                }
            </Form.Item>
        </Form.Item>

        <Form.Item
            label='其他选项'
            name='configName'
            wrapperCol={{ span: 8 }}>
            <Input addonBefore={<span>配置名称:</span>} ></Input>
        </Form.Item>

    </Form>;
}

export default SearchTool